package com.itheima.interceptor;

import com.itheima.utils.CurrentHolder;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        log.info("执行TokenInterceptor 拦截器:postHandle");
//        if ("OPTIONS".equals(request.getMethod())) {
//            return true;
//        }
//        if(true){
//            CurrentHolder.setUserId(1);
//            return true;
//        }

        String token = request.getHeader("token");
        try {
            Claims claims = JwtUtils.parseJWT(token);
            Integer userId = claims.get("userId", Integer.class);
            CurrentHolder.setUserId(userId);
        } catch (Exception e) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("执行TokenInterceptor拦截器");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        CurrentHolder.removeThread();
        log.info("CurrentHolderThread 清理完成");
    }
}
